package com.vision.web;

import com.alibaba.fastjson.JSON;
import com.vision.common.bean.CommonResult;
import com.vision.common.exception.CodeException;
import com.vision.common.util.HttpIPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @Filename ExcHandler.java
 * @Description
 * @Version 1.0
 * @Author zhongc
 * @Email zhong_ch@foxmail.com
 * @History <li>Author: zhongc</li>
 * <li>Date: 2017/6/1</li>
 * <li>Version: 1.0</li>
 * <li>Content: create</li>
 */
@ControllerAdvice
public class ExcHandler {
    public static final Logger LOGGER = LoggerFactory.getLogger(ExcHandler.class);

    @ExceptionHandler(value = CodeException.class)
    @ResponseBody
    public CommonResult codeExceptionHandler(HttpServletRequest req, CodeException e) throws Exception {
        StringBuilder sb = new StringBuilder();
        req.getParameterMap().forEach((k, v) -> sb.append(k).append(":{").append(JSON.toJSONString(v)).append("}"));
        LOGGER.warn("异常请求 ip:{},request url:{}, params:{}", HttpIPUtil.getIpAddr(req),
                req.getRequestURI(), sb.toString(), e);

        CommonResult result = new CommonResult();
        result.setSuccess(false);
        result.setDesc("错误请求");
        return result;
    }

}
